package flutter.dio.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/user")
public class TestController {
    static Map<String, UserBean> userBeanMap = new HashMap<>();

    static {
        UserBean userBean1 = new UserBean(1, "张三", 22, "北京某公司招聘事业处");
        UserBean userBean2 = new UserBean(2, "李四", 23, "上海某公司后勤事业处");
        userBeanMap.put("张三", userBean1);
        userBeanMap.put("李四", userBean2);
    }

    @RequestMapping("info")
    public R getUserInfo(@RequestParam String userName) {

        UserBean userBean = userBeanMap.get(userName);

        if (userBean == null) {
            return R.error(402, "未查询到用户");
        }
        return R.okData(userBean);

    }

    @PostMapping("register")
    public R registerUserInfo(@RequestBody UserBean userBean) {

        String userName = userBean.getUserName();
        if (userName == null) {
            return R.error(402, "请输入用户名");
        }
        int size = userBeanMap.entrySet().size();
        userBean.setUserId(size);
        userBeanMap.put(userName, userBean);
        return R.okData(userBean);
    }

    @RequestMapping("list")
    public R getUserList() {

        List<UserBean> userBeanList = new ArrayList<>();
        for (Map.Entry<String, UserBean> stringUserBeanEntry : userBeanMap.entrySet()) {
            userBeanList.add(stringUserBeanEntry.getValue());
        }
        return R.okData(userBeanList);

    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

    @PostMapping("file/upload")
    public R upload(MultipartFile uploadFile, HttpServletRequest req) {
        if (uploadFile == null) {
            return R.error(402, "请选择文件! ");
        }
        String realPath =
                req.getSession().getServletContext().getRealPath("/uploadFile/");
        String format = sdf.format(new Date());
        File folder = new File(realPath + format);
        String filePath = "";
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() +
                oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            uploadFile.transferTo(new File(folder, newName));
            filePath = req.getScheme() + "://" + req.getServerName() + ":" +
                    req.getServerPort() + "/uploadFile/" + format + newName;

        } catch (IOException e) {
            e.printStackTrace();
            return R.error(402, "上传失败! ");
        }

        return R.okData(filePath);
    }
}
